package com.sans.common.util;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Objects;
/**
 * @title: EncryptUtil
 * @Author 王康
 * @Date: 2023/1/4 17:34
 * @Version 1.0
 */
public class EncryptUtil {
    // 密钥
    public static String key = "LmMHSTGtOpF4xNyvYt54EQ==";

    //spring MD5偏移量32；securityMD5偏移量16
    private static Integer OFFSET = 32;

    public static String encode(String xmlStr) {
        byte[] encrypt = null;

        try {
            // 取需要加密内容的utf-8编码。
            encrypt = xmlStr.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 取MD5Hash码，并组合加密数组
        byte[] md5Hasn = null;
        try {
            md5Hasn = EncryptUtil.MD5Hash(encrypt, 0, encrypt.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 组合消息体
        byte[] totalByte = EncryptUtil.addMD5(md5Hasn, encrypt);

        // 取密钥和偏转向量
        byte[] key = new byte[8];
        byte[] iv = new byte[8];
        getKeyIV(EncryptUtil.key, key, iv);
        SecretKeySpec deskey = new SecretKeySpec(key, "DES");
        IvParameterSpec ivParam = new IvParameterSpec(iv);

        // 使用DES算法使用加密消息体
        byte[] temp = null;
        try {
            temp = EncryptUtil.DES_CBC_Encrypt(totalByte, deskey, ivParam);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用Base64加密后返回
        return new BASE64Encoder().encode(temp);
    }

    public static String decode(String xmlStr) {
        // base64解码
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] encBuf = null;
            try {
                encBuf = decoder.decodeBuffer(xmlStr);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 取密钥和偏转向量
            byte[] key = new byte[8];
            byte[] iv = new byte[8];
            getKeyIV(EncryptUtil.key, key, iv);

            SecretKeySpec deskey = new SecretKeySpec(key, "DES");
            IvParameterSpec ivParam = new IvParameterSpec(iv);

            // 使用DES算法解密
            byte[] temp = null;
            try {
                temp = EncryptUtil.DES_CBC_Decrypt(encBuf, deskey, ivParam);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 进行解密后的md5Hash校验
            byte[] md5Hash = null;
            try {
                md5Hash = EncryptUtil.MD5Hash(temp, OFFSET, temp.length - OFFSET);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 进行解密校检
            for (int i = 0; i < md5Hash.length; i++) {
                if (md5Hash[i] != temp[i]) {
                    // System.out.println(md5Hash[i] + "MD5校验错误。" + temp[i]);
                    throw new Exception("MD5校验错误。");
                }
            }

            // 返回解密后的数组，其中前16位MD5Hash码要除去。
            return new String(temp, OFFSET, temp.length - OFFSET, "utf-8");
        } catch (Exception e) {
            return null;
        }

    }

    public static byte[] TripleDES_CBC_Encrypt(byte[] sourceBuf,
                                               SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
        byte[] cipherByte;
        // 使用DES对称加密算法的CBC模式加密
        Cipher encrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");

        encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);

        cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);
        // 返回加密后的字节数组
        return cipherByte;
    }

    public static byte[] TripleDES_CBC_Decrypt(byte[] sourceBuf,
                                               SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {

        byte[] cipherByte;
        // 获得Cipher实例，使用CBC模式。
        Cipher decrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");
        // 初始化加密实例，定义为解密功能，并传入密钥，偏转向量
        decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);

        cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);
        // 返回解密后的字节数组
        return cipherByte;
    }

    public static byte[] DES_CBC_Encrypt(byte[] sourceBuf,
                                         SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
        byte[] cipherByte;
        // 使用DES对称加密算法的CBC模式加密
        Cipher encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");

        encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);

        cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);
        // 返回加密后的字节数组
        return cipherByte;
    }

    public static byte[] DES_CBC_Decrypt(byte[] sourceBuf,
                                         SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {

        byte[] cipherByte;
        // 获得Cipher实例，使用CBC模式。
        Cipher decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
        // 初始化加密实例，定义为解密功能，并传入密钥，偏转向量
        decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);

        cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);
        // 返回解密后的字节数组
        return cipherByte;
    }

//    public static byte[] MD5Hash(byte[] buf, int offset, int length)
//            throws Exception {
//        MessageDigest md = MessageDigest.getInstance("MD5");
//        md.update(buf, offset, length);
//        return md.digest();
//    }

    public static byte[] MD5Hash(byte[] buf, int offset, int length) throws Exception{
        byte[]  new_bts= Arrays.copyOfRange(buf, offset, length + offset);
        return DigestUtils.md5DigestAsHex(new_bts).getBytes();
    }

    public static String byte2hex(byte[] inStr) {
        String stmp;
        StringBuffer out = new StringBuffer(inStr.length * 2);

        for (int n = 0; n < inStr.length; n++) {
            // 字节做"与"运算，去除高位置字节 11111111
            stmp = Integer.toHexString(inStr[n] & 0xFF);
            if (stmp.length() == 1) {
                // 如果是0至F的单位字符串，则添加0
                out.append("0" + stmp);
            } else {
                out.append(stmp);
            }
        }
        return out.toString();
    }

    public static byte[] addMD5(byte[] md5Byte, byte[] bodyByte) {
        int length = bodyByte.length + md5Byte.length;
        byte[] resutlByte = new byte[length];

        // 前16位放MD5Hash码
        for (int i = 0; i < length; i++) {
            if (i < md5Byte.length) {
                resutlByte[i] = md5Byte[i];
            } else {
                resutlByte[i] = bodyByte[i - md5Byte.length];
            }
        }

        return resutlByte;
    }

    public static void getKeyIV(String encryptKey, byte[] key, byte[] iv) {
        // 密钥Base64解密
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = null;
        try {
            buf = decoder.decodeBuffer(encryptKey);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 前8位为key
        int i;
        for (i = 0; i < key.length; i++) {
            key[i] = buf[i];
        }
        // 后8位为iv向量
        for (i = 0; i < iv.length; i++) {
            iv[i] = buf[i + 8];
        }
    }
    /**
     * 加密
     * @param strPassword
     * @return
     */
    public static String EncodePassword(String strPassword){
        char code;
        String des = "";
        if(StringUtils.isEmpty(strPassword)){
            return des;
        }
        String strKey = EncipherConst.m_strKey1 + EncipherConst.m_strKey2 + EncipherConst.m_strKey3 + EncipherConst.m_strKey4 + EncipherConst.m_strKey5 + EncipherConst.m_strKey6;
        while(strPassword.length() < 8){
            strPassword = strPassword + (char)1;
        }
        for(int n = 0; n <= strPassword.length() - 1; n++){
            while(true){
                code = (char)Math.rint(Math.random() * 100);
                while((code > 0) && (((code ^ strPassword.charAt(n)) < 0) || ((code ^ strPassword.charAt(n)) > 90))){
                    code = (char)((int)code - 1);
                }
                char mid = 0;
                int flag;
                flag = code ^ strPassword.charAt(n);
                if(flag > 93){
                    mid = 0;
                } else{
                    mid = strKey.charAt(flag);
                }
                //确保生成的字符是可见字符并且在SQL语句中有效
                if((code > 35) & (code < 122) & (code != 124) & (code != 39) & (code != 44) & (mid != 124) & (mid != 39) & (mid != 44)){
                    break;
                }
            }
            char temp = 0;
            temp = strKey.charAt(code ^ strPassword.charAt(n));
            des = des + (char)code + temp;
        }
        return des;

    }

    /**
     * 解密
     * @param varCode
     * @return
     */
    public static String DecodePassword(String varCode){
        int n;
        String des = "";
        if((varCode == null) || (varCode.length() == 0)){
            return des;
        }
        String strKey = EncipherConst.m_strKey1 + EncipherConst.m_strKey2 + EncipherConst.m_strKey3 + EncipherConst.m_strKey4 + EncipherConst.m_strKey5 + EncipherConst.m_strKey6;
        if(varCode.length() % 2 == 1){
            varCode = varCode + "?";
        }
        for(n = 0; n <= varCode.length() / 2 - 1; n++){
            char b;
            b = varCode.charAt(n * 2);
            int a;
            a = (int)strKey.indexOf(varCode.charAt(n * 2 + 1));
            des = des + (char)((int)b ^ a);
        }
        n = des.indexOf(1);
        if(n > 0){
            return des.substring(0, n);
        } else{
            return des;
        }

    }

    /**
     * 拆分移位加盐16进制脱敏
     * @param number
     * @return
     */
    public static String encodeShiftSaltHex(Long number){

        if(!Objects.isNull(number)){
            String str = String.valueOf(number);
            int leftLength = str.length()/2 + 1;
            String leftStr = leftLength == 0 ? "" : str.substring(0, leftLength);
            String rightStr = "1" + str.substring(leftLength, str.length());

            if(!StringUtils.isEmpty(leftStr)){
                String leftHex = Long.toHexString(Long.valueOf(leftStr) * 2 + EncipherConst.salt_number);
                String rightHex = Long.toHexString(Long.valueOf(rightStr) * 2 + EncipherConst.salt_number);
                return leftHex.length() + leftHex + rightHex;
            }
        }

        return null;
    }

    /**
     * 拆分移位加盐16进制还原
     * @param cipher
     * @return
     */
    public static String decodeShiftSaltHex(String cipher){

        if(!StringUtils.isEmpty(cipher)){
            Integer leftLen = Integer.valueOf(cipher.substring(0,1));
            if(leftLen > 0 && cipher.length() > leftLen + 1){
                String leftHex = cipher.substring(1, leftLen + 1);
                String rightHex = cipher.substring(leftLen + 1);

                Long leftNum = (Long.parseLong(leftHex, 16) - EncipherConst.salt_number) / 2;
                Long rightNum = (Long.parseLong(rightHex, 16) - EncipherConst.salt_number) / 2;

                return leftNum + String.valueOf(rightNum).substring(1);
            }
        }

        return null;
    }


    static class EncipherConst{
        public final static String m_strKey1 = "zxcvbnm,./asdfg";

        public final static String m_strKey2 = "hjkl;'qwertyuiop";

        public final static String m_strKey3 = "[]\\1234567890-";

        public final static String m_strKey4 = "=` ZXCVBNM<>?:LKJ";

        public final static String m_strKey5 = "HGFDSAQWERTYUI";

        public final static String m_strKey6 = "OP{}|+_)(*&^%$#@!~";

        public  final static Long salt_number = 137520L;

    }

    public static void main(String[] args){
        //14790441892
        String mobile = "13365591011";
        String encode = EncryptUtil.encode(mobile);
        System.out.println("enncode:" + encode + ";length=" + encode.length());
        String decode = EncryptUtil.decode("kenPVJwLupTI2P7tXC7+kwQVvIFg6597GFFmoyvR5bY9irpa96V+ZF2ChAIk8iqS");
        System.out.println("decode:" + decode);



        String responseMessage = "successabc";
        String truncatedMessage = responseMessage.substring(0, Math.min(responseMessage.length(), 5));

        System.out.println(truncatedMessage);
        boolean a = false;
        boolean b = false;
        for (int i = 0; i < 10; i++) {
            a = i == 4;
            if (a) {
                for (int j = 0; j < 10; j++) {
                    b = j == 4;
                    if (b) {
                        break;
                    }
                }
            }
            System.out.println(i);
        }
        System.out.println(a);
        System.out.println(b);
    }
}
